package com.fh.util.cloc;

import java.util.ArrayList;
import java.util.List;

import org.apache.poi.xssf.usermodel.examples.FillsAndColors;

import com.fh.util.HttpUtil;
import com.fh.util.HttpUtil.HttpParam;
import com.google.gson.JsonObject;
import com.fh.util.PageData;

public class ClocUtil {
	
//	private static final String URL = "http://192.168.43.190:5000/";	// 本地测试
	private static final String URL = "http://115.29.99.187:5000/";	// 阿里云
	
	private static final String COMMIT_URL = "commit";
	private static final String QUERY_URL = "query";
	
	public static class queryResult{
		public boolean success;
		public int summary;
		public int comment;
		public int blank;
		public int code;
		public byte[] simhash = new byte[8];
		public String simhashCode;
	}
	
	
	public static void addTask(int solutionId,String gitUrl,String username,String password) throws Exception{
		String url = URL + COMMIT_URL;
		List<HttpParam> lParams = new ArrayList<HttpUtil.HttpParam>();
		lParams.add(new HttpParam("id", solutionId + ""));
		lParams.add(new HttpParam("url", gitUrl));
		if(username != null){
			lParams.add(new HttpParam("username", username));
		}
		if(password != null){
			lParams.add(new HttpParam("password", password));
		}
		JsonObject jObject = HttpUtil.postWithJsonRet(url, lParams);
		System.out.println("Clone返回提示信息");
		System.out.println(jObject);
		// 返回提示失败.抛出异常
	}
	
	public static queryResult queryTask(int solutionId) throws Exception{
		String url = URL + QUERY_URL;
		
		queryResult qResult = new queryResult();
		
		List<HttpParam> lParams = new ArrayList<HttpUtil.HttpParam>();
		lParams.add(new HttpParam("id", solutionId + ""));
		JsonObject jObject = HttpUtil.postWithJsonRet(url, lParams);
		System.out.println("查询结果");
		System.out.println(jObject);
		
		// 判断是否运算成功
		boolean success = jObject.get("success").getAsBoolean();
		qResult.success = success;
		if(success){
			JsonObject sumJson = jObject.getAsJsonObject("cloc").getAsJsonObject("SUM");
			System.out.println("代码总量");
			System.out.println(sumJson);
			qResult.blank = sumJson.get("blank").getAsInt();
			qResult.code = sumJson.get("code").getAsInt();
			qResult.comment = sumJson.get("comment").getAsInt();
			qResult.summary = qResult.blank + qResult.code + qResult.comment;
			
			String simhash = jObject.get("simhash").getAsString();
			System.out.println("Simhash");
			System.out.println(simhash);
			qResult.simhashCode= simhash;
			// 转化为byte数组
			for(int i = 0;i < 16;i += 2){
				String temp = simhash.substring(i, i+2);
				qResult.simhash[i/2] = (byte) Integer.parseInt(temp, 16);
			}
			System.out.println(qResult.simhash);
		}
		
		return qResult;
	}
	
	
	// 测试
	public static void main(String[] args){
		
		try {
			queryTask(2);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
